package com.wctj.api;

import com.google.common.base.CaseFormat;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.*;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.wctj.api.web.constants.ProjectConstant.MAPPER_PACKAGE;
import static com.wctj.api.web.constants.ProjectConstant.MODEL_PACKAGE;


/**
 * 代码生成器，根据数据表名称生成对应的Model、Mapper、Service、Controller简化开发。
 */
public class CodeGenerator {
    //JDBC配置，请修改为你项目的实际配置
//    private static final String JDBC_URL = "jdbc:mysql://121.40.157.212:3306/letuu";
//    private static final String JDBC_USERNAME = "letuu";
//    private static final String JDBC_PASSWORD = "5NwrAFYaeTXzXKXh";
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/payment";
    private static final String JDBC_USERNAME = "root";
    private static final String JDBC_PASSWORD = "123456";

//    private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
    private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";

    private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径
    private static final String TEMPLATE_FILE_PATH = PROJECT_PATH + "/zgzg-pay-web/src/test/resources/generator/template";//模板位置

    private static final String JAVA_PATH = "/src/main/java"; //java文件路径
    private static final String RESOURCES_PATH = "/src/main/resources";//资源文件路径

//    private static final String PACKAGE_PATH_SERVICE = packageConvertPath(SERVICE_PACKAGE);//生成的Service存放路径
//    private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(SERVICE_IMPL_PACKAGE);//生成的Service实现存放路径
//    private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(CONTROLLER_PACKAGE);//生成的Controller存放路径

    /** 可在Run/Debug Configurations CodeGenerator启动类配置 VM Options -Duser.name=XXX ，即可在注释中生成author，默认是使用计算机使用者名称如在windows下是Administrator*/
    private static final String AUTHOR = System.getProperty("user.name");//@author
//    private static final String AUTHOR = "liaozhanggen@126.com";//@author

    private static final String DATE = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//@date

    public static void main(String[] args) throws IOException {
        InputStream ins = null;
        try {
            ins = System.in;
            Scanner scanner = new Scanner(ins);
            while (true) {
                System.out.println("输入表名:Model类名【单个用t_user:User，多个用t_user:User,t_city:City(英文逗号隔开)】 输入end结束");
                String tableNameAndModelNameStr = null;
                tableNameAndModelNameStr = scanner.next();
                if ("end".equals(tableNameAndModelNameStr)) {
                    return;
                }
                StringTokenizer stringTokenizer = new StringTokenizer(tableNameAndModelNameStr, ",",
                    false);
                List<String> tableNameAndModelNameList = Lists.newArrayList();
                while (stringTokenizer.hasMoreElements()) {
                    tableNameAndModelNameList.add(stringTokenizer.nextToken());
                }
                for (String tableNameAndModelName : tableNameAndModelNameList) {
                    String[] arr = tableNameAndModelName.split(":");
                    genCode(arr[0], arr[1]);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ins.close();
        }
    }

    /**
     * 通过数据表名称生成代码，Model 名称通过解析数据表名称获得，下划线转大驼峰的形式。
     * 如输入表名称 "t_user_detail" 将生成 TUserDetail、TUserDetailMapper、TUserDetailService ...
     * @param tableNames 数据表名称...
     */
    public static void genCode(String... tableNames) {
        for (String tableName : tableNames) {
            genCode(tableName, null);
        }
    }

    /**
     * 通过数据表名称，和自定义的 Model 名称生成代码
     * 如输入表名称 "t_user_detail" 和自定义的 Model 名称 "User" 将生成 User、UserMapper、UserService ...
     * @param tableName 数据表名称
     * @param modelName 自定义的 Model 名称
     */
    public static void genCode(String tableName, String modelName) {
        genModelAndMapper(tableName, modelName);

    }


    public static void genModelAndMapper(String tableName, String modelName) {
        Context context = new Context(ModelType.FLAT);
        context.setId("Potato");
        context.setTargetRuntime("MyBatis3Simple");
        context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
        context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`");

        JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
        jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
        jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
        jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
        jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
        context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);

//        PluginConfiguration pluginConfiguration = new PluginConfiguration();
//        pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
//        pluginConfiguration.addProperty("mappers", "org.apache.ibatis.annotations.Mapper");
//        context.addPluginConfiguration(pluginConfiguration);

        JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
        javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + "/module-base/"+ JAVA_PATH);
        javaModelGeneratorConfiguration.setTargetPackage(MODEL_PACKAGE);
        javaModelGeneratorConfiguration.addProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS,"true");
        javaModelGeneratorConfiguration.addProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS,"false");

        context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);

        SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
        sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + "/module-business/module-business-common/"+ RESOURCES_PATH);
//        sqlMapGeneratorConfiguration.setTargetPackage("META-INF/mapper");
        sqlMapGeneratorConfiguration.setTargetPackage("mapper");
        context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);

        CommentGeneratorConfiguration commentGeneratorCfg = new CommentGeneratorConfiguration();
        commentGeneratorCfg.addProperty("suppressDate","true");
        commentGeneratorCfg.addProperty("suppressAllComments","true");
        commentGeneratorCfg.addProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS,"true");
//        commentGeneratorCfg.setConfigurationType("org.mybatis.generator.internal.DefaultCommentGenerator");
        commentGeneratorCfg.setConfigurationType("com.zgzg.shop.pay.CustomCommentGenerator");

        context.setCommentGeneratorConfiguration(commentGeneratorCfg);

        JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
        javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + "/module-business/module-business-common/"+  JAVA_PATH);
        javaClientGeneratorConfiguration.setTargetPackage(MAPPER_PACKAGE);
        javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
        context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);

        TableConfiguration tableConfiguration = new TableConfiguration(context);
        tableConfiguration.setTableName(tableName);
        tableConfiguration.setDomainObjectName(modelName);
        tableConfiguration.setGeneratedKey(new GeneratedKey("id", "Mysql", true, null));
        context.addTableConfiguration(tableConfiguration);

        List<String> warnings = new ArrayList<String>();
        MyBatisGenerator generator;
        try {
            Configuration config = new Configuration();
            config.addContext(context);
            config.validate();

            boolean overwrite = true;
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            warnings = new ArrayList<String>();
            generator = new MyBatisGenerator(config, callback, warnings);
            generator.generate(null);
        } catch (Exception e) {
            throw new RuntimeException("生成Model和Mapper失败", e);
        }

        if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
            throw new RuntimeException("生成Model和Mapper失败：" + warnings);
        }
        if (StringUtils.isEmpty(modelName)) modelName = tableNameConvertUpperCamel(tableName);
        System.out.println(modelName + ".java 生成成功");
        System.out.println(modelName + "Mapper.java 生成成功");
        System.out.println(modelName + "Mapper.xml 生成成功");
    }



    private static String tableNameConvertUpperCamel(String tableName) {
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase());

    }

    private static String tableNameConvertMappingPath(String tableName) {
        tableName = tableName.toLowerCase();//兼容使用大写的表名
        return (tableName.contains("_") ? tableName.replaceAll("_", "/") : tableName);
    }

    private static String modelNameConvertMappingPath(String modelName) {
        return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelName);
    }

    private static String packageConvertPath(String packageName) {
        return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName);
    }

}
